﻿namespace MvcXRepairCustomer.Services
{
    using System.Collections.Generic;
    using MvcXRepairCustomer.Interfaces;
    using MvcXRepairCustomer.Repository.SQL;
    using XRepair.Models;
    using System;
    using MvcXRepair.ViewModel;
    using Newtonsoft.Json;
    using MvcXRepair.Models;

    public class OrderService : IOrderService
    {
        private OrderDAO _orderRepository;

        public OrderService()
        {
            _orderRepository = new OrderDAO();
        }

        public IEnumerable<Order> GetAllActiveOrders()
        {
            return _orderRepository.GetAllActiveOrders();
        }

        public bool DeactivateOrderByID(int orderId)
        {
            return _orderRepository.DeactivateOrderByID(orderId);
        }

        public bool AddNewOrder(Order order)
        {
            order.CreatedAt = DateTime.Now;
            return _orderRepository.AddNewOrder(order);
        }

        public bool UpdateOrder(Order order)
        {
            order.LastUpdatedAt = DateTime.Now;
            return _orderRepository.UpdateOrder(order);
        }

        public bool AddPendingOrder(string username, OrderViewModel model)
        {
            string address = JsonConvert.SerializeObject(model.Address);
            string device = JsonConvert.SerializeObject(model.Device);
            string selectedSymptoms = JsonConvert.SerializeObject(model.SelectedSymptoms);

            string[] orderInfo = new string[] { address, device, selectedSymptoms };

            return _orderRepository.AddPendingOrder(username, orderInfo);
        }

        public OrderViewModel GetPendingOrderViewModelByUsername(string username)
        {
            string[] orderInfo = _orderRepository.GetPendingOrderByUsername(username);
            OrderViewModel lastOrder = null;

            if (orderInfo != null && orderInfo.Length == 3)
            {
                lastOrder = new OrderViewModel();

                lastOrder.Address = JsonConvert.DeserializeObject<Address>(orderInfo[0]);
                lastOrder.Device = JsonConvert.DeserializeObject<Device>(orderInfo[1]);
                lastOrder.SelectedSymptoms = JsonConvert.DeserializeObject<SymptomSelectViewModel>(orderInfo[2]);
            }

            return lastOrder;
        }
    }
}
